package com.sxt.service.impl;

import cn.hutool.core.date.DateUtil;
import com.sxt.common.CodeMsg;
import com.sxt.common.Constant;
import com.sxt.common.PageInfo;
import com.sxt.common.Result;
import com.sxt.dao.CustomerDao;
import com.sxt.dao.VisitLogDao;
import com.sxt.pojo.Customer;
import com.sxt.pojo.VisitLog;
import com.sxt.service.ICustomerService;

import java.util.Map;

public class CustomerServiceImpl implements ICustomerService {

    private CustomerDao customerDao = new CustomerDao();
    private VisitLogDao visitLogDao = new VisitLogDao();

    @Override
    public Result queryPage(Map<String, String> params, Integer pageNo, Integer pageSize) {
        PageInfo<Customer> data = customerDao.selectPage(params,pageNo,pageSize);
        return new Result(data);
    }

    @Override
    public Result add(String name, String phone, String sex, String company, Integer id) {
        //业务数据校验
        //手机号唯一校验
        Customer customer = customerDao.selectByPhone(phone);
        if (customer != null){
            return new Result(CodeMsg.CUSTOMER_PHONE_EXIST_ERROR);
        }
        //新增客户信息
        customerDao.insert(name,phone,sex,company,id);
        return new Result();
    }


    @Override
    public Result update(String id, String name, String phone, String sex, String company, Integer id1) {
        //业务数据校验
        //手机号唯一校验
        Customer customer = customerDao.selectByPhone(phone);
        //客户存在 且两个客户的ID 不一致  说明其它客户也使用该手机号
        if (customer != null && !customer.getId().equals(Integer.parseInt(id))){
            return  new Result(CodeMsg.CUSTOMER_PHONE_EXIST_ERROR);
        }
        customerDao.update(name,phone,sex,company,id);
        return new Result();
    }

    @Override
    public Result delete(String id) {
        customerDao.updateState(id, Constant.CUSTOMER_DELETE_ED);
        return new Result();
    }

    @Override
    public Result batchSetSalesman(String userId, String[] cIds) {
        customerDao.updateSalesman(userId,cIds);
        return new Result();
    }


    @Override
    public Result addVisitLog(String id, String name, Integer userId, String realname, String visitTime, String descp) {
        VisitLog visitLog = new VisitLog();
        visitLog.setUserId(userId);
        visitLog.setRealname(realname);
        visitLog.setCustomerId(Integer.parseInt(id));
        visitLog.setName(name);
        visitLog.setVisitTime(DateUtil.parse(visitTime,"yyyy-MM-dd"));
        visitLog.setDescp(descp);
        visitLogDao.insert(visitLog);
        return new Result();
    }
}
